import ipaddress
import platform
import subprocess
from typing import List, Tuple

class IPChecker:
    @staticmethod
    def is_private_ip(ip: str) -> bool:
        """检查是否是私有IP地址"""
        try:
            ip_obj = ipaddress.ip_address(ip)
            return ip_obj.is_private or ip_obj.is_loopback or ip_obj.is_link_local
        except ValueError:
            return True

    @staticmethod
    def ping(ip: str) -> bool:
        """ping IP地址检查是否可达"""
        try:
            # 根据操作系统选择ping命令参数
            param = '-n' if platform.system().lower() == 'windows' else '-c'
            command = ['ping', param, '1', ip]
            
            # 执行ping命令
            result = subprocess.run(command, 
                                 stdout=subprocess.PIPE, 
                                 stderr=subprocess.PIPE,
                                 timeout=2)  # 2秒超时
            
            return result.returncode == 0
        except (subprocess.TimeoutExpired, subprocess.SubprocessError):
            return False

    @classmethod
    def filter_public_ips(cls, ipv4s: List[str], ipv6s: List[str]) -> Tuple[List[str], List[str]]:
        """过滤并只保留可访问的公网IP地址"""
        public_ipv4s = []
        public_ipv6s = []

        # 检查IPv4地址
        for ip in ipv4s:
            if not cls.is_private_ip(ip) and cls.ping(ip):
                public_ipv4s.append(ip)

        # 检查IPv6地址
        for ip in ipv6s:
            if not cls.is_private_ip(ip) and cls.ping(ip):
                public_ipv6s.append(ip)

        return public_ipv4s, public_ipv6s